

#include <cecore/cefile.h>


ceFile::ceFile (const ceString& filename)
	: iFile ()
	, file (0)
	, filename (filename)
{
	IQF_CONSTRUCT;
}


IQF_IMPLEMENTATION_BEGIN(ceFile);
IQF_IMPLEMENTATION_INTERFACE(iFile);
IQF_IMPLEMENTATION_END();

bool ceFile::Open (int mode)
{
	if (	mode & OM_Write 
		&&	mode & OM_Text)
	{
		file = fopen (filename.c_str (), "wt");
	}
	else if (	mode & OM_Read
				&&	mode & OM_Text)
	{
		file = fopen (filename.c_str (), "rt");
	}
	else if (mode & OM_Write)
	{
		file = fopen (filename.c_str (), "wb");
	}
	else if (	mode & OM_Read)
	{
		file = fopen (filename.c_str (), "rb");
	}

	return file != 0;
}

bool ceFile::IsOpen () const
{
	return file != 0;
}

void ceFile::Close ()
{
	fclose (file);
	file = 0;
}

size_t ceFile::Write (const void* src, size_t size)
{
	return fwrite (src, sizeof (char), size, file);
}

size_t ceFile::Write (const ceString& text)
{
	return Write (text.c_str (), text.length());
}

size_t ceFile::Read (void* dst, size_t size)
{
	return fread (dst, sizeof (char), size, file);
}

void ceFile::Seek (SeekPos pos, long offset)
{
	int origin;
	switch (pos)
	{
	case SP_Cur:
		origin = SEEK_CUR;
		break;
	case SP_End:
		origin = SEEK_END;
		break;
	case SP_Set:
		origin = SEEK_SET;
		break;
	}
	fseek (file, offset, origin);
}


long ceFile::Tell () const
{
	return ftell (file);
}
